<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use addons\zzuser\service\EncryptS;
use app\common\controller\Api;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

class LoginBySms extends Api
{
    protected $noNeedLogin = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'mobile' => 'require|regex:1\d{10}|unique:user,username',
            'sms'    => 'require',
        ])) {
            $this->error($validate->getError());
        }
        $mobile   = input('mobile');
        $password = input('password');
        $sms      = input('sms');
        if (!$sms || Sms::check($mobile, $sms)) {
            $this->error('error sms');
        }
        $user = UserM::where('mobile', $mobile)->find();
        if (!$user) {
            $salt = Random::alnum();
            $user = UserM::create([
                'status'   => UserM::STATUS_NORMAL,
                'salt'     => $salt,
                'password' => EncryptS::password($password, $salt),
                'username' => $mobile,
                'nickname' => $mobile,
                'mobile'   => $mobile,
                'joinip'   => request()->ip(),
                'jointime' => time(),
            ]);
        }
        if ($user['status'] == UserM::STATUS_NORMAL) {
            $this->auth->direct($user['id']);
            $this->success('', [
                'token' => $this->auth->getToken(),
            ]);
        }
        $this->error();
    }
}
